If you made a photocopy of a sheet of paper, you would have two sheets of paper.
==
the second sheet?
No; they are separate objects, with equivalent data.
equals()
to the second sheet?
Yes; the data on both sheets is equivalent.
Strings are very common in programs,
so Java optimizes their use.
Usually if you need a string in your program you create it as follows.
Notice that new
is not needed.
String str = "String Literal" ;
This creates a string literal that contains the characters
String
).
The compiler keeps track of the literals in your program and
will reuse the same object if it can.
(The compiler will not try to reuse other types of
objects. String literals are special.)
For example, say that a program contained the following statements:
String str1, str2; str1 = "String Literal" ; str2 = "String Literal" ;
Only one object will be created, containing the characters
str1
nor
str2
because strings can't be changed).
There is no need for two string objects whose content is
identical.
This is different from this situation:
String strA, strB; strA = new String("My String") ; strB = new String("My String") ;
In the above situation, two objects are created, containing identical data. The compiler does not try to reuse the first object.
How many objects are created by the following code:
String msg1, msg2, msg3; msg1 = "Look Out!" ; msg2 = "Look Out!" ; msg3 = "Look Out!" ;